package org.example;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; // 需要添加Jackson依赖
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

import static org.example.AES_ECB.decrypt;
import static org.example.AES_ECB.encrypt;

public class sendJsonPostRequest {
    /**
     * 发送JSON格式的POST请求
     *
     * @param urlStr 请求地址
     * @param data   嵌套数据结构
     * @return 响应内容
     */
    private static final boolean AES_MODE = false;   //是否加密传输
    public static final String AES_KEY128 = "123abcABC"; //加密密钥（要和api接口服务相同）

    public static String sendJsonPostRequest(Map<String, Object> data) throws Exception {
        String urlStr = "http://192.168.23.233:9098/apiserver"; //配置Api服务地址

        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        // 设置请求方法为POST并允许输出
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);

        // 设置JSON请求头
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Accept", "application/json");

        Map<String, Object> jsonMap = new HashMap<>();
        jsonMap.put("openid", "000001");  //配置商户号（openid）

        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String timestamp = now.format(formatter);
        jsonMap.put("timestamp", timestamp);

        ObjectMapper mapper = new ObjectMapper();
        if (AES_MODE) {
            String jsonDataString = mapper.writeValueAsString(data);
            String dataEncrypt = encrypt(jsonDataString);
            jsonMap.put("data", dataEncrypt); // 嵌套对象
        }
        else {
            jsonMap.put("data", data); // 嵌套对象
        }
        // 使用Jackson将Map转换为JSON字符串
        String jsonInputString = mapper.writeValueAsString(jsonMap);
        //{"data":{"empid":"10998","pagesize":"100","pageindex":"1","id":"A01"},"openid":"000001","timestamp":"20250416102239"}

        // 发送JSON数据
        try (OutputStream os = conn.getOutputStream()) {
            byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
        }

        // 读取响应
        int responseCode = conn.getResponseCode();
        System.out.println("响应码: " + responseCode);

        if (responseCode == HttpURLConnection.HTTP_OK) { // 成功
            try (BufferedReader in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = in.readLine()) != null) {
                    response.append(line);
                }

                if (AES_MODE) {
                    return decrypt(response.toString());
                }
                else {
                    return response.toString();
                }
            }
        } else { // 错误处理（如400、500等）
            try (BufferedReader errorIn = new BufferedReader(
                    new InputStreamReader(conn.getErrorStream(), StandardCharsets.UTF_8))) {
                StringBuilder errorResponse = new StringBuilder();
                String line;
                while ((line = errorIn.readLine()) != null) {
                    errorResponse.append(line);
                }
                return "错误响应：\n" + errorResponse.toString();
            }
        }
    }
}